import React, { Component } from 'react'
import './Flower.css'

class Flower extends Component {
    state = {
        getButton:'获得鲜花数据', 
        list:[], 
        showList:JSON.parse(localStorage.getItem('flower')) || [],
    }
    //获得网页素材
    get = ()=>{
        this.setState({getButton:'鲜花列表'})
        fetch('https://www.fastmock.site/mock/3c02a69b3952632e311022710cb48a6c/plant/getPlants')
            .then(res=>res.json())   //返回Promise，解析为JSON
            .then(res=>{
                console.log(res)
                this.setState({list:res.result.plantList})
            })
            
        console.log(this)
    }
    //点击收藏事件
    change = (e)=>{
        //indexOf 要检索的字符串没有出现，则返回-1，在showList中检索
        if(this.state.showList.indexOf(e) === -1){
            this.setState({
            showList:[ e, ...this.state.showList]
            },()=>{
                //本地存储，刷新后依旧显示之前收藏的数据
                localStorage.setItem('flower', JSON.stringify(this.state.showList))
            })
        }
    }
    //删除事件
    delItem = (i)=>{
        let delList = this.state.showList.filter( (item, index)=> i!=index)
        this.setState({ showList:delList})
        localStorage.setItem("flower",JSON.stringify(delList))
    }

    render() {
        return (
            <div>
                <div className="collect">
                    <h2>已收藏鲜花列表</h2>
                    <ul>
                        {
                            this.state.showList.map ( (item, index) => <li key={item.plantID}>
                                {item.plantID}
                                ---
                                {item.name}             
                                <button onClick={()=> this.delItem(index)}>取消收藏</button>
                            </li>)
                        }
                    </ul>
                </div>
                <button onClick={this.get} className="getButton">{this.state.getButton}</button>
                <ul className="flower">
                    {
                        this.state.list.map( item =>{
                            return <li key={item.plantID}>
                                <img src={item.coverURL} />
                                <p>{item.name}</p>
                                <p>{item.engName}</p>
                                <p>产地：{item.area || '产地未知'}</p>
                                <button onClick={()=>this.change(item)}>
                                    {this.state.showList.indexOf(item) === -1? '收藏' :'已收藏'}
                                </button>
                                </li>
                                
                            
                        })
                    }
                </ul>
            </div>
        )
    }
}

export default Flower;
